import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import { View, Text, StyleSheet, ScrollView, Image } from 'react-native'
import { ScaleS, ScaleT, ONE_PIXEL } from 'src/utils/ScreenUtil'
import { LinearTextGradient } from 'react-native-text-gradient'
import { companyApplyNoticed } from 'src/utils/RequestAPI'
import CustomButton from 'src/components/button/CustomButton'
import NextButton from 'src/components/button/NextButton'
import CustomImage from 'src/components/image/CustomImage'
import CompanyApplySuccessPop from './CompanyApplySuccessPop'
import { SwitchRole } from 'src/components/modal/SwitchRoleModal'
/* redux */
import { connect } from 'react-redux'
import {
  UPDATE_USERINFO_ACTION
} from 'src/store/actions/userinfo'
import { DO_REQUEST_MAIN_PAGE_B_ACTION, DO_REQUEST_CHANGE_COMPANY_INFO_ACTION } from 'src/pageB/main/main-page/store/action'

const mapActiontoProps = dispatch => ({
  updateUserInfo (payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  doRequestMainPage (payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestUpdateCompanyInfo (...payload) {
    const promise = DO_REQUEST_CHANGE_COMPANY_INFO_ACTION(...payload)
    dispatch(promise)
    return promise.payload
  },
  doRequestUserCompanyApplyApply (payload) {
    const promise = DO_REQUEST_MAIN_PAGE_B_ACTION(payload)
    dispatch(promise)
    return promise.payload
  }
})

class CompanyApplyNotComplete extends React.PureComponent {
  static propTypes = {
    navigation: PropTypes.object,
    userId: PropTypes.number,
    userinfo: PropTypes.object,
    companyApplyNotComplete: PropTypes.bool,
    haveCompanyApply: PropTypes.object,
    updateUserInfo: PropTypes.func,
    doRequestMainPage: PropTypes.func,
    doRequestUserCompanyApplyApply: PropTypes.func
  }

  constructor (props) {
    super(props)
    this.state = {
    }
  }

  componentDidMount () {
    this.configState()
  }

  componentDidUpdate (prevProps, prevState) {
    const { userId, haveCompanyApply, userinfo: { B: { userId: userIdB } = {} } = {} } = this.props
    const { userId: userIdP, haveCompanyApply: haveCompanyApplyP, userinfo: { B: { userId: userIdBP } = {} } = {} } = prevProps
    if (userId !== userIdP || userIdB !== userIdBP || haveCompanyApply !== haveCompanyApplyP) {
      console.log(this.props.haveCompanyApply)
      this.configState(this.props)
    }
  }

  configState = props => {
    const {
      haveCompanyApply: {
        type,
        checkStatus,
        checkReason,
        companyName,
        simpleName,
        isNotice
      },
      userinfo: { B: { userId: userIdB } = {} } = {},
      userId
    } = props || this.props
    // 0-审核未通过 1-审核通过 2-待审核 company operator
    let tipTitle
    let tipDesc
    let nextBtnText
    let successApply
    let successApplyNotEnsure
    let successApplyPopTitle
    let successApplyCompanyVisible
    let successApplyOperatorVisible
    if (!userId) {
      nextBtnText = '去登录'
    } else if (!userIdB) {
      nextBtnText = '去完善信息'
    } else {
      switch (checkStatus) {
        case 0:
          switch (type) {
            case 'company':
              tipTitle = `您的审核被驳回`
              tipDesc = `驳回原因：${checkReason}`
              nextBtnText = '重新申请'
              break
            case 'operator':
              tipTitle = `${simpleName || companyName}未通过您的申请，\n请重新申请`
              nextBtnText = '重新申请'
              break
            default:
              break
          }
          break
        case 1:
          successApply = true
          if (isNotice !== '1') {
            successApplyNotEnsure = true
            switch (type) {
              case 'company':
                successApplyPopTitle = '恭喜，您的公司已通过审核\n请输入公司简称'
                successApplyCompanyVisible = true
                break
              case 'operator':
                successApplyPopTitle = `恭喜，${simpleName || companyName}已通过您的申请`
                successApplyOperatorVisible = true
                break
              default:
                break
            }
          } else {
            successApplyNotEnsure = false
          }
          break
        case 2:
          tipTitle = null
          tipDesc = null
          nextBtnText = '审核中'
          this.refreshApplyState()
          break
        case '':
          tipTitle = null
          tipDesc = null
          nextBtnText = '去完成审核'
          break
        default:

          break
      }
    }
    this.setState({
      tipTitle,
      tipDesc,
      nextBtnText,
      successApply,
      successApplyNotEnsure,
      successApplyPopTitle,
      successApplyCompanyVisible,
      successApplyOperatorVisible
    })
  }

  componentWillUnmount () {
    this.clearRefreshTimer()
  }

  refreshApplyState = (dealy = 15000) => {
    this.clearRefreshTimer()
    this.refreshTimer = setTimeout(() => {
      const {
        userId,
        navigation
      } = this.props
      if (userId && navigation.isFocused()) {
        this.props.doRequestUserCompanyApplyApply({ userId }).finally(() => {
          const { joinCompany } = this.configState()
          this.setState({
            joinCompany
          })
        })
      } else {
        this.refreshApplyState()
      }
    }, dealy)
  }

  clearRefreshTimer = () => {
    this.refreshTimer && clearTimeout(this.refreshTimer)
    this.refreshTimer = null
  }

  render () {
    const { companyApplyNotComplete, navigation: { isFocused } } = this.props
    if (!companyApplyNotComplete) {
      return null
    }
    const {
      tipTitle,
      tipDesc,
      nextBtnText,
      successApply,
      successApplyNotEnsure,
      successApplyPopTitle,
      successApplyCompanyVisible,
      successApplyOperatorVisible
    } = this.state
    return (
      <Fragment>
        {!successApply && (
          <Fragment>
            <ScrollView
              style={styles.container}
              contentContainerStyle={styles.contentContainer}
            >
              <Text style={styles.text1}>完成招聘者审核，找到属于你的人才</Text>
              <LinearTextGradient
                style={styles.text2}
                locations={[0, 1]}
                colors={['#65D797', '#5DC9C5']}
                start={{ x: 0, y: 0 }}
                end={{ x: 0, y: 1 }}
              >
                更可获得以下权益
              </LinearTextGradient>
              <View style={styles.imgWraps}>
                <View style={styles.imgWrap}>
                  <Text style={styles.imgText}>发布岗位</Text>
                  <CustomImage
                    style={styles.img1}
                    source={require('src/imgC/company/prefixQuotation.png')}
                  />
                  <CustomImage
                    style={styles.img2}
                    source={require('src/imgC/company/publish.png')}
                  />
                </View>
                <View style={styles.imgWrap}>
                  <Text style={styles.imgText}>人才沟通</Text>
                  <CustomImage
                    style={styles.img1}
                    source={require('src/imgC/company/prefixQuotation.png')}
                  />
                  <CustomImage
                    style={styles.img2}
                    source={require('src/imgC/company/communicate.png')}
                  />
                </View>
              </View>
              {!!tipTitle && <Text style={styles.tipTitle}>{tipTitle}</Text>}
              {!!tipDesc && <Text style={styles.tipDesc}>{tipDesc}</Text>}
            </ScrollView>
            <View style={styles.bottomWrap}>
              <CustomButton
                style={styles.moreBtn}
                onPress={this.switchBtnClick}
              >
                <Text style={styles.moreTxt}>切换身份</Text>
              </CustomButton>
              <NextButton
                style={styles.bottomBtn}
                title={nextBtnText}
                onPress={this.bottomBtnClick}
                enable={true}
              />
            </View>
          </Fragment>
        )}
        {isFocused && !!successApply && !!successApplyNotEnsure && (
          <CompanyApplySuccessPop
            title={successApplyPopTitle}
            visible={successApplyCompanyVisible}
            onConfirm={this.onApplySuccessCompanyConfirm}
            onModalHide={this.onApplySuccessCompanyModalHide}
          />
        )}
        {isFocused && !!successApply && !!successApplyNotEnsure && (
          <CompanyApplySuccessPop
            title={successApplyPopTitle}
            visible={successApplyOperatorVisible}
            onConfirm={this.onApplySuccessOperatorConfirm}
            onModalHide={this.onApplySuccessOperatorModalHide}
          />
        )}
      </Fragment>
    )
  }

  _loginJump = () => {
    const {
      userinfo: {
        userId,
        B: { userId: userIdB } = {}
      }
    } = this.props
    if (!userId) {
      this.props.navigation.navigate('OneLogin')
      return true
    }
    if (!userIdB) {
      this.props.navigation.navigate('BFirstUserInfo')
      return true
    }
  }

  bottomBtnClick = () => {
    if (this._loginJump()) {
      return
    }
    // 0-审核未通过 1-审核通过 2-待审核 company operator
    const {
      haveCompanyApply: { type, checkStatus },
      navigation
    } = this.props
    if (type === 'none') {
      navigation.navigate('BCompanyApplyName')
    } else if (type === 'company') {
      navigation.navigate('BCompanyApplyLicence')
    } else if (type === 'operator') {
      if (checkStatus === 0) {
        navigation.navigate('BCompanyApplyName')
      } else {
        navigation.navigate('BCompanyApplyJoin')
      }
    }
  }

  /* 申请未成功 */
  switchBtnClick = () => {
    console.log('switchCellClick')
    SwitchRole()
  }

  /* 申请成功 */
  // 暂存创建企业简称
  onApplySuccessCompanyConfirm = () => {
    console.log('onApplySuccessCompanyConfirm')
    const { doRequestUpdateCompanyInfo, haveCompanyApply: { companyId }, userId, doRequestMainPage } = this.props
    const saveCallback = simpleName => {
      if (simpleName) {
        doRequestUpdateCompanyInfo({ params: { simpleName, companyId } })
      }
    }
    this.toggleVisible('successApplyCompanyVisible', false)
    this.props.navigation.navigate('CommonInputPage', {
      title: '企业简称',
      desc: '*请填写企业简称',
      placeholder: '请输入',
      maxLength: 10,
      saveCallback
    })
    companyApplyNoticed({
      params: {
        companyId,
        type: 'company',
        userId
      }
    }).then(() => {
      doRequestMainPage({ userId })
    })
  }

  onApplySuccessCompanyModalHide = () => {
    console.log('onApplySuccessCompanyModalHide')
  }

  onApplySuccessOperatorConfirm = () => {
    console.log('onApplySuccessOperatorConfirm')
    this.toggleVisible('successApplyOperatorVisible', false)
    const { haveCompanyApply: { companyId }, userId } = this.props
    companyApplyNoticed({ params: {
      companyId,
      type: 'operator',
      userId
    } })
  }

  onApplySuccessOperatorModalHide = () => {
    console.log('onApplySuccessOperatorModalHide')
    this.props.doRequestMainPage()
  }

  /* public  */
  toggleVisible = (key, value) => {
    this.setState({
      [key]: value
    })
  }
}
export default connect(
  ({ userinfo, BMineCenterStore }) => {
    const userIdB = userinfo.B.userId

    const {
      haveCompanyApply: { type, checkStatus }
    } = BMineCenterStore
    // 0-审核未通过 1-审核通过 2-待审核 company operator
    const companyApplyNotComplete =
    !userIdB ||
      (type === 'none' || (type !== 'none' && !isNaN(checkStatus)))
    // debugger
    return {
      userId: userinfo.userId,
      userinfo,
      haveCompanyApply: BMineCenterStore.haveCompanyApply,
      companyApplyNotComplete
    }
  },
  mapActiontoProps
)(CompanyApplyNotComplete)
const styles = StyleSheet.create({
  container: {
    backgroundColor: '#ffffff',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0
  },
  contentContainer: {
    paddingTop: ScaleS(90),
    paddingHorizontal: ScaleS(24),
    alignItems: 'center'
  },
  text1: {
    fontSize: ScaleT(18),
    fontWeight: '400',
    color: '#666666',
    lineHeight: ScaleS(38)
  },
  text2: {
    fontSize: ScaleT(22),
    fontWeight: '500',
    lineHeight: ScaleS(42)
  },
  imgWraps: {
    width: '100%',
    marginTop: ScaleS(80),
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  imgWrap: {
    width: ScaleS(151),
    height: ScaleS(128),
    backgroundColor: '#F9F9F9',
    borderRadius: ScaleS(5),
    position: 'relative'
  },
  imgText: {
    marginTop: ScaleS(30),
    marginLeft: ScaleS(12),
    fontSize: ScaleT(18),
    fontWeight: '300',
    color: '#999999',
    lineHeight: ScaleS(28)
  },
  img1: {
    position: 'absolute',
    top: ScaleS(11),
    left: ScaleS(12)
  },
  img2: {
    position: 'absolute',
    right: ScaleS(9),
    bottom: ScaleS(12)
  },
  tipTitle: {
    marginTop: ScaleS(20),
    fontSize: ScaleT(18),
    fontWeight: '500',
    color: '#000000',
    textAlign: 'center',
    lineHeight: ScaleS(32)
  },
  tipDesc: {
    marginTop: ScaleS(8),
    fontSize: ScaleT(14),
    fontWeight: '400',
    color: '#444444',
    lineHeight: ScaleS(24)
  },
  bottomWrap: {
    position: 'absolute',
    bottom: 0,
    height: ScaleS(133),
    left: 0,
    width: '100%',
    alignItems: 'center',
    backgroundColor: '#ffffff'
  },
  moreBtn: {
    paddingHorizontal: ScaleS(10),
    height: ScaleS(28),
    borderRadius: ScaleS(14),
    borderColor: '#999999',
    borderWidth: ONE_PIXEL,
    borderStyle: 'solid',
    justifyContent: 'center',
    alignItems: 'center'
  },
  moreTxt: {
    fontSize: ScaleT(12),
    fontWeight: '600',
    color: '#999999'
  },
  bottomBtn: {
    marginTop: ScaleS(25)
  }
})
